package com.bestvike.stone.spring.shiro.annotation.handler;

import com.bestvike.stone.spring.shiro.SecurityUtils;
import com.bestvike.stone.spring.shiro.annotation.RequiresRoles;
import com.bestvike.stone.spring.shiro.authz.exception.AuthorizationException;
import com.bestvike.stone.spring.shiro.authz.exception.authz.UnauthorizedException;

import java.lang.annotation.Annotation;

/**
 * 角色注解处理器
 */
public final class RoleAnnotationHandler implements AuthorizingAnnotationHandler {
    /**
     * 获取支持的注解类型
     */
    @Override
    public Class<? extends Annotation> getAnnotationClass() {
        return RequiresRoles.class;
    }

    /**
     * 断言权限
     */
    @Override
    public void assertAuthorized(Annotation annotation) throws AuthorizationException {
        RequiresRoles requiresRoles = (RequiresRoles) annotation;
        final String[] roles = requiresRoles.value();
        if (roles.length == 0)
            throw new UnauthorizedException("no roles set for RequiresRoles");
        switch (requiresRoles.logical()) {
            case AND:
                final boolean hasAllRole = SecurityUtils.hasAllRole(roles);
                if (!hasAllRole)
                    throw new UnauthorizedException();
                break;
            case OR:
                final boolean hasAnyRole = SecurityUtils.hasAnyRole(roles);
                if (!hasAnyRole)
                    throw new UnauthorizedException();
            default:
                break;
        }
    }
}
